﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ScratchNet
{
    public class ListRandomExpression : Expression
    {
        public Expression Count { get; set; }
        public Expression Min { get; set; }
        public Expression Max { get; set; }
        public override string ReturnType => "any";
        

        public override Descriptor Descriptor
        {
            get
            {
                Descriptor desc = new Descriptor();
                desc.Add(new TextItemDescriptor(this, "randomList("));
                desc.Add(new ExpressionDescriptor(this, "Count", "any"));
                desc.Add(new TextItemDescriptor(this, ","));
                desc.Add(new ExpressionDescriptor(this, "Min", "any"));
                desc.Add(new TextItemDescriptor(this, ","));
                desc.Add(new ExpressionDescriptor(this, "Max", "any"));
                desc.Add(new TextItemDescriptor(this, ")"));
                return desc;
            }
        }

        public override string Type => "ListAddExpression";

        protected override Completion ExecuteImpl(ExecutionEnvironment enviroment)
        {
            if (Count== null)
                return Completion.Exception("Null Exception", this);
            var count = GetValue(enviroment,Count);
            var min = GetValue(enviroment, Min);
            var max = GetValue(enviroment, Max);
            List<object> list = new List<object>();
            var r = new Random();
            for (int i = 0; i < count; i++)
            {
                list.Add(r.Next(min, max));
            }
            return new Completion(list);
        }

        private int GetValue(ExecutionEnvironment enviroment,Expression expression)
        {
            Completion v = expression.Execute(enviroment);
            if (!v.IsValue)
                return -1;

            return (int) v.ReturnValue;
        }
    }
}
